home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: pstaite@vnet.ibm.com
- Newsgroups: comp.lang.c++
- Subject: Re: How do I prevent deleting of an object that is still being used?
- Date: 16 Jan 1996 16:07:51 GMT
- Organization: IBM OS/2 Device Driver Development Rochester, MN
- Message-ID: <4dgign$11vi@locutus.rchland.ibm.com>
- References: <4dg9in$s5h@utopia.hacktic.nl>
- Reply-To: pstaite@vnet.ibm.com
- NNTP-Posting-Host: warpone.rchland.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4dg9in$s5h@utopia.hacktic.nl>, Mike Tavares <MIKET@cdynamics.com> writes:
- >
- >I have some classes:
-
- This problem cries out for reference counting ... :-) See additions to
- your classes below:
-
- >class menuItem
- > {
- > ...
-
- public:
- menuItem() : refs( 1 ) {}
- void dropref() { if( ! --refs ) delete this; }
- void addref() { ++refs; }
- private:
- int refs;
- > }
-
- Note, copy construction should set the ref count to 1 on the new
- menuItem, but leave the source object's ref count alone. Assignment
- should leave the ref counts of both objects alone.
-
- >
- >
- >
- >class menu
- > {
- >
- > list<menuItem> theItems // the items that are on this menu.
-
- Looks like the menu is owning it's own copy (by value) of the items.
- Maybe you meant:
-
- list<menuItem*> theItems;
-
-
-
- Register( menuItem &anItem ) {
- anItem.addref();
- theItems.add( &anItem ); }
-
- ~menu() {
- // for each menuItem in theItems
- theItems.remove( next_item )->dropref();
- }
-
- One caution: make sure the list doesn't try to do anything with the
- menuItems once you've called dropref() on them. After that call,
- they may be gone. You might want to extract/remove the element
- (ptr/ref) from the list then call dropref() on it.
-
-
- Phil Staite, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-
-